package query

import (
	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/bi/cube"
	"strconv"
	"time"
)

//GetUserDiviKeys 获取用户的认定关系的键值
func GetUserDiviKeys(diviName string, date *time.Time, emid int) ([]string, error) {
	month := date.Format("200601")
	divi, err := cube.NewDivision(diviName)
	if err != nil {
		return nil, err
	}
	return divi.GetRelation(month, strconv.Itoa(emid))
}

//GetOrganDiviKeys 获取部门下所有用户认定关系的键值
func GetOrganDiviKeys(diviName string, date *time.Time, dpid int) ([]string, error) {
	month := date.Format("200601")
	divi, err := cube.NewDivision(diviName)
	if err != nil {
		return nil, err
	}
	lev, _, err := cube.GetLevel("员工.部门-员工.所属部门")
	if err != nil {
		return nil, err
	}
	userKeys, err := lev.GetLeafKeys(strconv.Itoa(dpid))
	if err != nil {
		return nil, err
	}
	ywids := make([]string, 0, 100)
	for _, userKey := range userKeys {
		emid, err := strconv.Atoi(userKey)
		if err != nil {
			return nil, err
		}
		keys, err := divi.GetRelation(month, strconv.Itoa(emid))
		if err != nil {
			return nil, err
		}
		ywids = append(ywids, keys...)
	}
	return ywids, nil
}

//GetParentOrganDiviKeys 获取管辖部门下所有用户认定关系的键值
func GetParentOrganDiviKeys(diviName string, date *time.Time, dpid int) ([]string, error) {
	month := date.Format("200601")
	divi, err := cube.NewDivision(diviName)
	if err != nil {
		return nil, err
	}
	lev, _, err := cube.GetLevel("员工.部门-员工.管辖部门")
	if err != nil {
		return nil, err
	}
	userKeys, err := lev.GetLeafKeys(strconv.Itoa(dpid))
	if err != nil {
		return nil, err
	}
	ywids := make([]string, 0, 100)
	for _, userKey := range userKeys {
		emid, err := strconv.Atoi(userKey)
		if err != nil {
			return nil, err
		}
		keys, err := divi.GetRelation(month, strconv.Itoa(emid))
		if err != nil {
			return nil, err
		}
		ywids = append(ywids, keys...)
	}
	return ywids, nil
}

//GetBusinessUserDivis 获取业务分配的员工认定关系
func GetBusinessUserDivis(diviName string, date *time.Time, ywid string) (map[string]float64, error) {
	month := date.Format("200601")
	divi, err := cube.NewDivision(diviName)
	if err != nil {
		return nil, err
	}
	diviMap, err := divi.GetDivision(month, ywid)
	if err != nil {
		return nil, err
	}
	lev, _, err := cube.GetLevel("员工.部门-员工.员工名称")
	if err != nil {
		return nil, err
	}
	retDivi := make(map[string]float64)
	for k, v := range diviMap {
		keyVal, err := lev.GetNameByKey(k)
		if err != nil {
			return nil, err
		}
		retDivi[base.ToString(keyVal.Value)] = v
	}
	return retDivi, nil
}
